package com.zyk.scaffold.oauth.config.oauth.grant;

import com.zyk.scaffold.oauth.component.TenantCodeCachComponent;
import com.zyk.scaffold.oauth.config.oauth.support.LocalUserDetailsService;
import com.zyk.scaffold.oauth.framework.domain.ClientDetails;
import com.zyk.scaffold.oauth.framework.domain.OauthContext;
import com.zyk.scaffold.oauth.framework.domain.OauthRequest;
import com.zyk.scaffold.oauth.framework.domain.UserDetails;
import com.zyk.scaffold.oauth.framework.interfaces.IClientDetailsService;
import com.zyk.scaffold.oauth.framework.interfaces.ITokenGranter;
import com.zyk.scaffold.common.utils.AssertUtil;
import com.zyk.scaffold.common.utils.MapUtils;
import com.zyk.scaffold.user.dto.UserBasicInfoDTO;
import com.zyk.scaffold.user.rpc.UserRpcService;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;

@Slf4j
public class SsoJwtGranter implements ITokenGranter {
    private String grantType = "sso_jwt";
    private IClientDetailsService clientDetailsService;
    private LocalUserDetailsService localUserDetailsService;
    private UserRpcService userRpcService;
    private TenantCodeCachComponent tenantCodeCachComponent;

    public SsoJwtGranter(IClientDetailsService clientDetailsService, LocalUserDetailsService localUserDetailsService, UserRpcService userRpcService, TenantCodeCachComponent tenantCodeCachComponent) {
        this.clientDetailsService = clientDetailsService;
        this.localUserDetailsService = localUserDetailsService;
        this.userRpcService = userRpcService;
        this.tenantCodeCachComponent = tenantCodeCachComponent;
    }

    @Override
    public OauthContext grant(OauthRequest request) {
        String clientId = request.getClientId();
        String account = request.getAccount();
        HashMap<String, String> requestParam = request.getRequestParam();
        String name = MapUtils.getString(requestParam, "name");
        String mobile = MapUtils.getString(requestParam, "mobile");
        String email = MapUtils.getString(requestParam, "email");
        ClientDetails clientDetails = this.clientDetailsService.loadClientDetailsByClientId(clientId);
        AssertUtil.notNull(clientDetails, "客户端不存在,禁止登录");
        UserBasicInfoDTO userBasicInfoDTO = new UserBasicInfoDTO();
        userBasicInfoDTO.setAccount(account);
        userBasicInfoDTO.setEmail(email);
        userBasicInfoDTO.setName(name);
        userBasicInfoDTO.setPhone(mobile);
        userRpcService.updateUserBasicInfo(userBasicInfoDTO);
        String tenantCode = tenantCodeCachComponent.getTenantCode(account);
        UserDetails userDetails = this.localUserDetailsService.loadTenantUserDetails(account, tenantCode);
        AssertUtil.notNull(userDetails, "账号不存在,禁止登录");
        return new OauthContext(userDetails, request, clientDetails);
    }

    @Override
    public String getGrantType() {
        return grantType;
    }
}
